package com.snoopy.gas1.controller;

//import com.snoopy.boot.demos.web.config.RedisUtil;
import com.snoopy.gas1.entity.Oil_info;
import com.snoopy.gas1.entity.Sales_record;
import com.snoopy.gas1.mapper.Sales_recordMapper;
import com.snoopy.gas1.service.Oil_infoService;
import com.snoopy.gas1.service.SalesRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/salesRecord")
public class Sales_recordController {
    @Autowired
    SalesRecordService salesRecordService;
    @Autowired
    private Oil_infoService oilInfoService; // 注意变量名规范（小驼峰）



    @GetMapping("/list")
    public String list(Model model) {
        List<Sales_record> salesRecordList = salesRecordService.lists();
        model.addAttribute("salesRecords", salesRecordList);
        return "salesRecord/list";
    }

    // 按客户名查询
    @GetMapping("/search")
    public String searchByCustomer(@RequestParam(value ="customer", required = false) String customer, Model model) {
        System.out.println("customer:" + customer);
        List<Sales_record> salesRecords;
//        System.out.println("salesRecords:" + salesRecords);
        String query = (customer != null) ? customer.trim() : ""; // 去除前后空格

        if (query.isEmpty()) {
            salesRecords = salesRecordService.lists();
        } else {
            salesRecords = salesRecordService.searchByCustomer(query);
        }
        model.addAttribute("salesRecords", salesRecords);
        System.out.println("传递到页面的变量名：salesRecords，数据：" + salesRecords);
        return "salesRecord/list";
    }

    // 删除
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") int id) {
        salesRecordService.delete(id);
        return "redirect:/salesRecord/list";
    }

    // 跳转添加页面
    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("salesRecord", new Sales_record());
        model.addAttribute("oils", oilInfoService.getAllOils()); // 添加油品列表
        return "salesRecord/add";  // 对应 templates/salesRecord/add.html
    }


    // 保存添加
    @PostMapping("/save")
    public String save(
            @ModelAttribute Sales_record salesRecord,  // 使用 @ModelAttribute 明确绑定表单数据
            Model model,
            BindingResult bindingResult  // 用于接收数据绑定错误
    ) {
        // 打印接收到的数据（调试用）
        System.out.println("Received salesRecord: " + salesRecord);

        // 检查数据绑定是否出错
        if (bindingResult.hasErrors()) {
            model.addAttribute("errorMsg", "表单数据有误，请检查！");
            bindingResult.getAllErrors().forEach(error ->
                    System.out.println("Error: " + error.getDefaultMessage())
            );
            return "salesRecord/add";
        }

        try {
            int result = salesRecordService.add(salesRecord);
            if (result > 0) {
                return "redirect:/salesRecord/list";
            } else {
                model.addAttribute("errorMsg", "添加失败，请重试！");
                return "salesRecord/add";
            }
        } catch (RuntimeException e) {
            model.addAttribute("errorMsg", e.getMessage());
            return "salesRecord/add";
        }
    }

    // 跳转编辑页面
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable int id, Model model) {
        Sales_record salesRecord = salesRecordService.getById(id);
        model.addAttribute("salesRecord", salesRecord);
        // 传递oil_info表中所有有效油品
        model.addAttribute("oilList", Oil_infoService.listAll());
        return "salesRecord/edit";
    }
    // 更新
    @PostMapping("/update")
    public String update(Sales_record salesRecord, Model model) {
        try {
            // 若Service执行成功（无异常），则必然跳转
            salesRecordService.update(salesRecord);
            return "redirect:/salesRecord/list"; // 成功则跳转
        } catch (Exception e) {
            // 仅在异常时停留在编辑页（如记录不存在）
            model.addAttribute("errorMsg", e.getMessage());
            model.addAttribute("salesRecord", salesRecord);
            return "salesRecord/edit";
        }
    }
    // 统计接口
    @GetMapping("/statistics")
    @ResponseBody
    public Map<String, Object> getStatistics(Sales_recordMapper salesRecordMapper) {
//        Sales_recordMapper salesRecordMapper = null; // 需通过@Autowired注入
        List<Sales_record> records = salesRecordMapper.getSalesRecords();
        List<String> customers = new ArrayList<>();
        List<Double> quantities = new ArrayList<>(); // 修正为Double类型
        for (Sales_record record : records) {
            customers.add(record.getCustomer());
            quantities.add((double) record.getSalesQuantity()); // 类型匹配
        }
        Map<String, Object> result = new HashMap<>();
        result.put("customers", customers);
        result.put("quantities", quantities);
        return result;
    }

    // 注册
//    @PostMapping("/register")
//    public String register(Sales_record salesRecord,
//                           @RequestParam("inputCode") String inputCode,
//                           Model model) {
//        String code = redisUtil.getCode("code");
//        if (code == null) {
//            model.addAttribute("msg", "验证码已过期");
//            return "register";
//        }
//        if (!code.equals(inputCode)) {
//            model.addAttribute("msg", "验证码错误");
//            return "register";
//        }
//        salesRecordService.register(salesRecord);
//        return "index";
//    }
}